package cn.flying.base.web.auth.configuration;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import cn.flying.base.web.auth.domain.SysUserRole;
import cn.flying.base.web.auth.service.SysUserService;

/**
 * @description: 自定义动态加载用户信息数据服务
 * @author: lvyong
 * @date: 2022年11月07日 20:57
 * @version: 1.0
 */
@Component
public class LoginUserDetailService implements UserDetailsService {

    @Resource
    private SysUserService sysUserService;

    /**
     * 加载用户信息
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LoginUser loginUser = sysUserService.findUserByUsername(username);
        if (loginUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        //加载用户的角色权限
        List<SysUserRole> list = sysUserService.getUserRoleList(loginUser.getUserId());
        if (CollectionUtils.isEmpty(list)) {
            return loginUser;
        }

        //加载用户所有的权限资源 TODO
        List<String> authorities = new ArrayList<>();

        //处理角色，增加前缀“ROLE_”
        List<String> roles = list.stream().map(sysUserRole -> "ROLE_" + sysUserRole.getRoleId()).collect(Collectors.toList());

        authorities.addAll(roles);

        //包装当前用户的权限到
        loginUser.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(String.join(",", authorities)));
        return loginUser;
    }
}
